/**
 * ProductController
 * @Chunning.Xu
 * 2011 Nov 23, 2011 10:52:52 AM
 **/
package com.lux.product.controllers
{
	import com.lux.product.models.ProductModel;
	import com.lux.product.swfaddress.SWFAddress;
	import com.lux.product.views.ProductOverEffect;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.external.ExternalInterface;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	public class ProductController extends LuxViewController
	{
		//START.
		
		private var bitmapData:BitmapData;
		private var _opacRect:Rectangle;
		private var transButton:Sprite;
		
		private var effect:ProductOverEffect;
		
		public function ProductController(product:ProductModel = null)
		{
			super(new Sprite);
			this.product = product;
		}
		
		private var _product:ProductModel;
		public function set product(_product:ProductModel):void
		{
			if(_product == null || this._product == _product)
				return;
			this._product = _product;
			this.bitmapData = product.image;
			
			initialize();
		}
		
		public function get product():ProductModel
		{
			return _product;
		}
		
		private function initialize():void
		{
			var bitmap:Bitmap = new Bitmap(bitmapData);
			bitmap.smoothing = true;
			view.addChild(bitmap);			
			
			_opacRect = bitmapData.getColorBoundsRect(0xAA000000,0xAA000000,true);
			
			transButton = new Sprite;
			transButton.buttonMode = true;
			view.addChild(transButton);
			transButton.graphics.beginFill(0xFF9900,0);
			transButton.graphics.drawRect(opacRect.x,opacRect.y,opacRect.width,opacRect.height);
			transButton.graphics.endFill();
			transButton.addEventListener(MouseEvent.CLICK,clickHandler);
			
			effect = new ProductOverEffect(opacRect);
			view.addChild(effect);
			
			transButton.addEventListener(MouseEvent.MOUSE_OVER,function(evt:Event):void{effect.play()});
			transButton.addEventListener(MouseEvent.MOUSE_OUT,function(evt:Event):void{effect.stop();});
		}
		
		private function clickHandler(evt:Event):void
		{
			if(product.tracking.click != null)
				ExternalInterface.call("_gaq.push",["_trackEvent",product.tracking.click,"click"]);
			SWFAddress.setValue(product.label);
		}
		
		public function get opacRect():Rectangle
		{
			return _opacRect;
		}
		
		public function set enabled(enabled:Boolean):void
		{
			transButton.mouseEnabled = enabled;	
			
			if(enabled && opacRect.contains(view.mouseX,view.mouseY))
				effect.play();
			else
				effect.stop();
		}
		
		public function get enabled():Boolean
		{
			return transButton.mouseEnabled;
		}
		
		//END
	}
}